package com.qcby.lxt.framedemo.interceptor;

import com.qcby.lxt.framedemo.annotation.NoNeedToken;
import com.qcby.lxt.framedemo.entity.Test;
import com.qcby.lxt.framedemo.exception.NeedToLoginException;
import com.qcby.lxt.framedemo.exception.UserNotExistException;
import com.qcby.lxt.framedemo.service.TestService;
import com.qcby.lxt.framedemo.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @className: AuthenticationInterceptor
 * @description:
 * @author: lxt
 * @create: 2021-04-19 10:31
 **/
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private TestService testService;
    //Controller逻辑执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        // 从请求头中取出 token  这里需要和前端约定好把jwt放到请求头一个叫token的地方
        String token = request.getHeader("token");
        // 如果不是映射到controller方法直接通过
        // ResourceHttpRequestHandler 是静态资源,无需拦截
        // HandlerMethod 是Controller中的方法
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查是否有NoNeedToken注释，有则跳过认证
        if (method.isAnnotationPresent(NoNeedToken.class)) {
                return true;
        }
        //默认全部检查
        else {
            // 执行认证
            if (token == null) {
                //这里其实是登录失效,没token了
                throw new NeedToLoginException();
            }
            // 获取 token 中的 userId
            String userId = JwtUtil.getAudience(token);
            Test user = testService.getById(userId);
            if (user == null) {
                //这个错误也是我自定义的
                throw new UserNotExistException();
            }
            // 验证 token
            JwtUtil.verifyToken(token, userId);
            return true;
        }
    }

    //Controller逻辑执行完毕但是视图解析器还未进行解析之前
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        log.info("postHandle....");
    }
    //Controller逻辑和视图解析器执行完毕
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        log.info("afterCompletion....");
    }
}
